<template>
  <view class="container">
    <view class="head">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <view class="item">
          <image src="/static/search-2.png" class="icon-search" />
          <input class="search-input" placeholder="搜索巡检项目、地点" />
        </view>
        <text class="search-btn">搜索</text>
      </view>
      <!-- 筛选标签 -->
      <view class="tabs">
        <text :class="['tab', activeTab === 0 ? 'active' : '']" @click="activeTab = 0">全部</text>
        <text :class="['tab', activeTab === 1 ? 'active' : '']" @click="activeTab = 1">正常</text>
        <text :class="['tab', activeTab === 2 ? 'active' : '']" @click="activeTab = 2">预警</text>
        <text :class="['tab', activeTab === 3 ? 'active' : '']" @click="activeTab = 3">异常</text>
      </view>
    </view>
    <!-- 任务列表 -->
    <scroll-view scroll-y class="task-list" :show-scrollbar="false">
      <view v-for="task in filteredTasks" :key="task.address_name" class="task-card">
        <view class="card-header">
          <text class="card-title">{{ task.address_name }}</text>
          <view :class="['status', task.result]" @click="handleStatusClick(task)">
            <view class="dot"></view>
            <text>{{ getStatusText(task.result) }}</text>
            <img v-if="task.icon" :src="task.icon" :style="{ width: '16px', height: '16px', color: task.iconColor }" />
          </view>
        </view>
        <!--进度条-->
        <view class="progress-bar">
          <view :class="['progress', task.result === 'warning' ? 'warning' : task.result === 'error' ? 'error' : '']" :style="{ width: task.progress + '%' }">
          </view>
        </view>
        <!--任务行-->
        <view class="subtasks">
          <view v-for="subtask in task.subtasks" :key="subtask.planContent" class="subtask">
            <view class="subtask-left">
              <view class="icon-and-name">
                <img v-if="subtask.icon" :src="subtask.icon" :style="{ width: subtask.size + 'px', height: subtask.size + 'px', color: subtask.color }" />
                <text>{{ subtask.planContent }}</text>
              </view>
              <text class="subtask-time">{{ subtask.start_time }}</text>
            </view>
            <view class="subtask-right">
              <text v-if="subtask.status" class="completed">已完成</text>
              <view v-else class="status-tag">
                <view class="inline-container">
                  <!-- 给文本添加 perform 类 -->
                  <text class="perform">进行中</text>
                  <view class="scan" @tap="handleScan(subtask,'normal')">
                    <img src="/static/scan-icon.png" style="width: 20px; height: 16px; margin-right: 5px;" />
                    <text>正常</text>
                  </view>
				  <view class="scan" @tap="handleScan(subtask,'error')" style="background-color:red">
				    <img src="/static/scan-icon.png" style="width: 20px; height: 16px; margin-right: 5px;" />
				    <text>异常</text>
				  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 底部导航 -->
    <!-- <view class="bottom-nav">
      <view class="nav-item" v-for="(item, index) in bottomNavs" :key="index" @click="goBottomNav(item.url, index)">
        <image :src="currentTab === index ? item.iconActive : item.icon" class="nav-icon" />
        <text :class="['nav-label', currentTab === index ? 'active' : '']">{{ item.label }}</text>
      </view>
    </view> -->
	<CustomBottomNav></CustomBottomNav>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import CustomBottomNav from '../common/tabar.vue';

const app = getApp();

const activeTab = ref(0); // 当前选中的标签索引
const photos = ref([]) // 全局缓存
// 根据 activeTab 的值筛选工单
const statusMap = {
  0: () => tasks.value,
  1: () => tasks.value.filter(task => task.result === 'normal'),
  2: () => tasks.value.filter(task => task.result === 'warning'),
  3: () => tasks.value.filter(task => task.result === 'error')
};

const filteredTasks = computed(() => {
  return (statusMap[activeTab.value] || statusMap[0])();
});

const currentTab = ref(2); // 修改为 2，让巡检图标初始变蓝
const bottomNavs = [
  { icon: '/static/home.png', iconActive: '/static/home-active.png', label: '首页', url: '/pages/index/index' },
  { icon: '/static/order.png', iconActive: '/static/order-active.png', label: '工单', url: '/pages/order/order' },
  { icon: '/static/check.png', iconActive: '/static/check-active.png', label: '巡检', url: '/pages/check/check' },
  { icon: '/static/user.png', iconActive: '/static/user-active.png', label: '我的', url: '/pages/user/user' }
]

// 跳转底部导航
const goBottomNav = (url, index) => {
  currentTab.value = index;
  uni.reLaunch({ url })
}


//任务列表
const tasks = ref([
  { address_name: '学生宿舍5公寓', result: 'normal', progress: 70, subtasks: [
    { planContent: '消防设备检查', icon: '/static/correct.png', size: 19, start_time: '09:30', status: true },
    { planContent: '电梯运行检查', icon: '/static/correct.png', size: 19, start_time: '10:15', status: true },
    { planContent: '公共区域卫生', icon: '/static/perform.png', size: 19, start_time: '11:00', status: false }
  ] },
  { address_name: '教学楼B座', result: 'warning', progress: 100, subtasks: [
    { planContent: '空调系统检查', icon: '/static/correct.png', size: 19, start_time: '08:30', status: true },
    { planContent: '照明设备检查', icon: '/static/correct.png', size: 19, start_time: '09:00', status: true },
    { planContent: '安全出口检查', icon: '/static/correct.png', size: 19, start_time: '09:30', status: true }
  ] },
  { address_name: '图书馆C座', result: 'error', progress: 30, subtasks: [
    { planContent: '消防设备检查', icon: '/static/perform.png', size: 19, start_time: '9:00', status: false },
    { planContent: '电梯运行检查', icon: '/static/perform.png', size: 19, start_time: '10:30', status: false },
	{ planContent: '公共区域卫生', icon: '/static/perform.png', size: 19, start_time: '11:30', status: true }
  ] }
]);

const getStatusText = (status) => {
  switch (status) {
    case 'normal': return '正常';
    case 'warning': return '预警';
    case 'error': return '异常';
    default: return '';
  }
};

const handleScan = (subtask,result) => {
	photos.value =[];
  uni.chooseImage({
    count: 9 - photos.value.length,        // 还能再选几张
    sizeType: ['compressed'],
    sourceType: ['camera', 'album'],       // 相机 + 相册
    success: (res) => {
      photos.value.push(...res.tempFilePaths)

      // 提示用户是否立即上传（可选）
      uni.showModal({
        title: '确认上传',
        content: `共选择 ${photos.value.length} 张照片，立即上传？`,
        success: (confirm) => {
          if (confirm.confirm) {
            uploadBatch(subtask.recordId,result)
          }
        }
      })
    },
    fail: () => uni.showToast({ title: '选取失败', icon: 'none' })
  })
}

/* 批量上传公共函数 */
const uploadBatch = async (recordId,result) => {
  if (!photos.value.length) {
    uni.showToast({ title: '请选择图片', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '上传中...' });

  try {
    // 使用 Promise.all 处理多张图片的上传任务
    const uploadPromises = photos.value.map((path) => {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: encodeURI(`${app.globalData.baseUrl}/InspectionPlan/daka`),
          filePath: path, // 图片的临时路径
          name: 'files', // 与后端 @RequestParam("files") 对应
          formData: {
            id: recordId,
			result:result
          },
          header: {
            'X-Tenant-Id': uni.getStorageSync('tenantId'),
            'token': uni.getStorageSync('token'),
          },
          success: (uploadRes) => {
            resolve(JSON.parse(uploadRes.data));
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    });

    // 等待所有上传任务完成
    const results = await Promise.all(uploadPromises);

    // 处理上传结果
    uni.hideLoading();
    uni.showToast({ title: '上传成功', icon: 'success' });
    photos.value = []; // 清空照片数组

    // 这里可以根据 results 处理后端返回的数据
    console.log('上传结果:', results);

  } catch (err) {
    uni.hideLoading();
    uni.showToast({ title: '上传失败', icon: 'none' });
    console.error('上传失败:', err);
  }
};

const handleStatusClick = (task) => {
  // 状态点击逻辑，可根据需求扩展
  console.log('点击了', task.title, '的状态：', task.status);
};
const get_record = ()=>{
	const baseUrl = app.globalData.baseUrl;
		uni.request({
		    url: encodeURI(baseUrl + '/InspectionPlan/selectAllGroupInspectionRecord'),
			method:'POST',
		    data: {
		    },
		    header:{
				"X-Tenant-Id": uni.getStorageSync("tenantId"),
				"token" : uni.getStorageSync("token")
			},
		    success: (res) => {
				console.log(res.data)
				tasks.value = res.data.data
		    }
		});

	}


// 在页面加载时设置 currentTab 为 2
onMounted(() => {
  currentTab.value = 2;
  get_record();
})

</script>

<style scoped>
.head {
  background: #fff;
}
.container {
  background: #EFEFEF;
  padding-bottom: 240rpx;
  min-height: 1200rpx;
}
/*搜索栏*/
.search-bar {
  display: flex;
  align-items: center;
  padding: 0 24rpx; /* 添加左右内边距 */
  margin: 16rpx 0;
}
.item {
  background: #FAFAFA;
  border-radius: 8rpx;
  padding: 16rpx 24rpx; /* 调整内边距 */
  flex: 1; /* 让搜索框部分占据剩余空间 */
  display: flex;
  align-items: center;
}
.icon-search {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
}
.search-input {
  flex: 1;
  border: none;
  background: transparent;
  margin: 0;
  font-size: 30rpx;
  color: #969696;
}
.search-btn {
  color: #007aff;
  font-size: 30rpx;
  margin-left: 16rpx;
  background: #fff;
  padding: 10rpx 32rpx; /* 调整按钮内边距 */
  border-radius: 8rpx;
  white-space: nowrap; /* 防止按钮文字换行 */
}
/*筛选标签*/
.tabs {
  display: flex;
  background: #fff;
  padding: 0 24rpx;
}
.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 32rpx;
  color: #4F4F4F;
  position: relative;
}
.tab.active {
  color: #007aff;
  font-weight: bold;
}
.tab.active::after {
  content: '';
  display: block;
  margin: 0 auto;
  width: 48rpx;
  height: 4rpx;
  background: #007aff;
  border-radius: 2rpx;
  margin-top: 8rpx;
}
/*任务列表*/
/* 任务栏 */
.task-list {
  padding: 24rpx;
}
.task-card {
  box-shadow: 0 4rpx 16rpx #eee;
  background: #fff;
  border-radius: 24rpx;
  padding: 28rpx;
  margin: 0 46rpx 24rpx 0rpx;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.card-title {
  font-weight: bold;
  font-size: 34rpx;
  color: #000;
}
.status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
}
.status .dot {
  width: 25rpx;
  height: 25rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}
.status text {
  font-size: 29rpx;
  margin-right: 10rpx;
  font-weight: bold;
}
/*点*/
.normal .dot {
  background: #07c160;
}
.normal text {
  color: #07c160;
}
.warning .dot {
  background: #ff9900;
}
.warning text {
  color: #ff9900;
}
.error .dot {
  background: #ff4d4f;
}
.error text {
  color: #ff4d4f;
}
/*进度条*/
.progress-bar {
  height: 20rpx;
  background: #E5E5E5;
  border-radius: 50rpx;
  margin-bottom: 15rpx;
}
.progress {
  height: 100%;
  background: #DCFCE7;
  border-radius: 50rpx;
}
.progress.warning {
  background: #DCFCE7;
}
.progress.error {
  background: #DCFCE7;
}
/*任务条*/
.subtasks {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  padding: 2rpx 2rpx;
  border-radius: 16rpx;
}
.subtask {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #F4F4F5;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  position: relative;
  flex-wrap: wrap; /* 允许子元素换行 */
}
/* 灰色条 */
.subtask::before {
  content: '';
  position: absolute;
  top: 0;
  left: 10%;
  width: 80%;
  height: 2rpx;
}
.subtask-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 15rpx;
}
.icon-and-name {
  display: flex;
  align-items: center;
  gap: 20rpx;
}
/*左侧字体*/
.subtask-left text {
  font-size: 31rpx;
  color: #000;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10rpx;
}
.subtask-left .subtask-time {
  font-size: 27rpx;
  color: #9A9A9A;
  margin-left: 50rpx;
}
.subtask-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
}
.completed {
  background-color: #DCFCE7;
  color: #337541;
  padding: 10rpx 20rpx;
  border-radius: 26rpx;
  font-weight: bold;
  margin: -34rpx 0 10rpx 0;
}
.status-tag .perform {
  background-color: #DBEAFE;
  color: #1E40AF;
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  font-weight: bold;
}
.scan {
  background-color: #fff;
  color: #000;
  padding: 12rpx 10rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
  font-weight: bold;
  white-space: nowrap; /* 防止文字换行 */
  flex-shrink: 0; /* 防止元素缩小 */
}
.inline-container {
  width: 100%; /* 占满一行 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 20rpx; /* 调整元素之间的间距 */
  margin-top: 10rpx;
  justify-content: flex-end;
  margin: -30rpx 0 10rpx 0;
}
/* 可根据需要调整文字不换行 */
.inline-container text {
  white-space: nowrap;
}
/*底部*/
.bottom-nav {
  position: fixed;
  bottom: 0;
  padding-bottom: 10rpx;
  width: 100%;
  height: 130rpx;
  background: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.nav-icon {
  width: 50rpx;
  height: 50rpx;
}
.nav-label {
  font-size: 26rpx;
  color: #000;
  margin-top: 4rpx;
}
.nav-label.active {
  color: #3D76FF;
}
</style>